package com.youthfilmic.yuejian.service;

import com.youthfilmic.yuejian.dao.SubjectDao;
import com.youthfilmic.yuejian.dao.UserDao;
import com.youthfilmic.yuejian.domain.Subject;
import com.youthfilmic.yuejian.domain.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by youweixi on 15/10/12.
 */
@Service
public class SubjectServiceImpl implements SubjectService {
    @Resource
    private UserDao userDao;
    @Resource
    private SubjectDao subjectDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleSubject(Long subjectId, int status, String reason) throws Exception {
        Subject subject = subjectDao.findOne(subjectId);
        if (subject == null) throw new Exception();
        else{
            subject.setHandleAt(new Date());
            if (status == 1){
                subject.setStatus(1);
            }else if (status == -1){
                subject.setStatus(-1);
            }else if (status == 0){
                subject.setStatus(0);
            }
            subjectDao.save(subject);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSubjectInfo(Long subjectId, Subject subject) {
        Subject s = subjectDao.findOne(subjectId);
        s.setPrice(subject.getPrice());
        s.setType(subject.getType());
        s.setContent(subject.getContent());
        s.setDuration(subject.getDuration());
        s.setTitle(subject.getTitle());
        subjectDao.save(s);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createSubject(Long userId, Subject subject) {
        User user = userDao.findOne(userId);
        subject.setUser(user);
        //居然有人喜欢发0元的话题
        if(subject.getPrice() <= 0) subject.setPrice(1);
        subject.setPostAt(new Date());
        subject.setUserId(userId);
        subject.setStatus(Subject.STATUS_WAIT_FOR_CERTIFICATION);
        subjectDao.save(subject);
        //用户的subjectCount增加
        userDao.incSubjectCount(userId , 1);
    }
}
